<!DOCTYPE html><!-- simplified doctype works for all previous versions of HTML as well -->

<!-- Paul Irish's technique for targeting IE, modified to only target IE6, applied to the html element instead of body -->
<!--[if lt IE 7 ]><html lang="en" class="no-js ie6"><![endif]-->
<!--[if (gt IE 6)|!(IE)]><!--><html lang="en" class="no-js"><!--<![endif]-->
<head>
  <meta charset="utf-8" />
  <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
       Remove this if you use the .htaccess -->
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

  <title>Hosts Template</title>
  <meta name="description" content="HTML5 template" />
  <meta name="author" content="Roger Xu" />

  <!-- Mobile viewport optimized: j.mp/bplateviewport -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <!-- Place favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
  <link rel="shortcut icon" href="/favicon.ico">
  <link rel="apple-touch-icon" href="/apple-touch-icon.png">

  <!-- CSS: implied media="all" -->
  <link rel="stylesheet" href="../css/style.css?v=2">

  <!-- Uncomment if you are specifically targeting less enabled mobile browsers
  <link rel="stylesheet" media="handheld" href="css/handheld.css?v=2">  -->

  <style>
    @import "http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/resources/dojo.css";
    @import "http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dijit/themes/claro/claro.css";
  </style>

  <!-- All JavaScript at the bottom, except for Modernizr which enables HTML5 elements & feature detects -->
  <script src="../script/modernizr-1.7.min.js"></script>

  <style>
    .code {
        font-family: "Consolas", "Lucida Console", "Courier New";
    }
  </style>
</head>
<body class="claro">

  <!-- First header has an ID so you can give it individual styles, and target stuff inside it -->
  <header id="hd1">
    <!-- "hgroup" is used to make two headings into one, to prevent a new document node from forming -->
    <hgroup>
      <h1>A Preview of HTML 5</h1>
      <h2 id="version">Unknown Version</h2>
    </hgroup>

    <!-- Main nav, styled by targeting "#hd1 nav"; you can have more than one nav element per page -->
    <nav>
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Contact</a></li>
      </ul>
    </nav>
  </header><!-- #hd1 -->

  <!-- This is the main "div" that wraps the content generically; don't use "section" for this -->
  <article id="main">

    <!-- The first of two "section" elements for demo purposes; optional class added for styling (hs1 = "home section 1") -->
    <section class="hs1">
    <!-- Each section should begin with a new h1 (not h2), and optionally a header -->
    <!-- You can have more than one header/footer pair on a page -->
      <header>
        <h1>Chapter 1: The Period</h1>
      </header>

      <p>
It was the best of times, it was the worst of times,
it was the age of wisdom, it was the age of foolishness,
it was the epoch of belief, it was the epoch of incredulity,
it was the season of Light, it was the season of Darkness,
...
      </p>

      <!-- The h2 below is a sub heading relative to the h1 in this section, not for the whole document -->
      <h2>Demonstrating EM and STRONG</h2>

      <!-- "strong" is used for SEO and contextual hierarchy -->
      <p><strong>This text will have more importance (SEO-wise and contextually)</strong></p>

      <!-- "b" is used for stylistic offset of text that's NOT important contextually -->
      <p><b>This text has visual importance but has no contextual or SEO importance</b></p>

      <!-- "em" is used for colloquial-style emphasis -->
      <p>This is a <em>very</em> colloquial expression.</p>

      <!-- There can be multiple footers on each page -->
      <!-- Secondary headers and footers don't necesarily need ids; they can be targeted via context (i.e. ".hs1 footer") -->
      <footer>
        <!-- incite a riot: http://24ways.org/2009/incite-a-riot -->
        <p>Author: <cite>Louis Lazaris</cite></p>
      </footer>

    </section><!-- .hs1 -->

    <!-- This is another section; doesn't have header/footer because it's not required -->
    <section class="hs2">
      <h1>This is another section</h1>
      <div id="borderContainer" data-dojo-type="dijit.layout.BorderContainer" style="height: 400px; border: 2px solid gray;">
        <div id="border-left" data-dojo-type="dijit.layout.ContentPane" data-dojo-props='region:"left", splitter:true' style="background-color: #aaa; width: 30%;">
          <textarea id="editor" name="srcTextarea" dojoType="dijit.form.SimpleTextarea" class="code" style="width:98%; height:98%;">No data</textarea>
        </div>
        <div id="border-center" data-dojo-type="dijit.layout.ContentPane" data-dojo-props='region:"center"' style="background-color: #f5ffbf;">
          <div data-dojo-type="dijit.Editor" id="richEditor">
            <p>No data</p>
          </div>
        </div>
        <div id="border-right" data-dojo-type="dijit.layout.ContentPane" data-dojo-props='region:"right", splitter:true' style="background-color: #aaa; width: 30%;">
          <textarea id="outEditor" name="srcTextarea" dojoType="dijit.form.SimpleTextarea" class="code" style="width:98%; height:98%;">No data</textarea>
        </div>
        <div id="border-bottom" data-dojo-type="dijit.layout.ContentPane" data-dojo-props='region:"bottom"' style="background-color: #b39b86;">
          <div id="toolbar" data-dojo-type="dijit.Toolbar">
            <input id="pattern" data-dojo-type="dijit.form.FilteringSelect"data-dojo-props='autoComplete:true, searchAttr:"host", onChange:selectPattern' />
            <input id="replacement" data-dojo-type="dijit.form.ComboBox" data-dojo-props='autoComplete:true, searchAttr:"ip"' />
            <div id="replaceButton" data-dojo-type="dijit.form.Button" data-dojo-props='onClick:replaceHost'>Replace</div>
            <span data-dojo-type="dijit.ToolbarSeparator"></span>
            <div id="replaceAllButton" data-dojo-type="dijit.form.Button" data-dojo-props='onClick:replaceAllHosts'>Replace All</div>
            <div id="jsButton" data-dojo-type="dijit.form.Button" data-dojo-props='onClick:generateTemplate'>Get Template Code</div>
          </div>
        </div>
      </div>
    </section><!-- .hs2 -->

  </article><!-- #main -->

  <!-- The "aside" element could be a sidebar (outside an article or section) -->
  <!-- Or it could reference other tangentially-related content within an article or section -->
  <aside>
    <h1>Archives</h1>
    <ul>
      <li><a href="/2007/09/">September 2007</a></li>
      <li><a href="/2007/08/">August 2007</a></li>
      <li><a href="/2007/07/">July 2007</a></li>
    </ul>
  </aside>

  <!-- The main footer has an ID for targeting, similar to the main header -->
  <footer id="f1">
    <p>copyright &copy; 2011</p>
  </footer><!-- #f1 -->

<!-- JavaScript at the bottom for fast page loading -->

<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if necessary -->
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js" data-dojo-config='parseOnLoad: true, isDebug: true, locale: "en"'></script>
<script>
    dojo.require("dojo.date.locale");
    dojo.require("dojo.parser");

    dojo.require("dijit.dijit"); // optimize: load dijit layer
    dojo.require("dijit.ColorPalette");
    dojo.require("dijit.Dialog");
    dojo.require("dijit.Editor");
    dojo.require("dijit.InlineEditBox");
    dojo.require("dijit.Menu");
    dojo.require("dijit.TitlePane");
    dojo.require("dijit.Toolbar");
    dojo.require("dijit.ToolbarSeparator");
    dojo.require("dijit.TooltipDialog");

    dojo.require("dijit.form.Button");
    dojo.require("dijit.form.CheckBox");
    dojo.require("dijit.form.ComboBox");
    dojo.require("dijit.form.DateTextBox");
    dojo.require("dijit.form.DropDownButton");
    dojo.require("dijit.form.FilteringSelect");
    dojo.require("dijit.form.Form");
    dojo.require("dijit.form.NumberSpinner");
    dojo.require("dijit.form.NumberTextBox");
    dojo.require("dijit.form.RadioButton");
    dojo.require("dijit.form.SimpleTextarea");
    dojo.require("dijit.form.Textarea");
    dojo.require("dijit.form.TextBox");
    dojo.require("dijit.form.ToggleButton");
    dojo.require("dijit.form.ValidationTextBox");

    dojo.require("dijit.layout.BorderContainer");
    dojo.require("dijit.layout.ContentPane");

    dojo.require("dojox.data.AndOrWriteStore");
    dojo.require("dojox.html.entities");

    dojo.require("dojox.layout.FloatingPane");
    dojo.require("dojox.layout.ResizeHandle");
    dojo.require("dojox.storage");
    dojo.require("dojox.validate");
    dojo.require("dojox.validate.web");
    dojo.require("dojox.widget.Standby");
    dojo.require("dojox.widget.Toaster");
</script>

<!-- scripts concatenated and minified via ant build script-->
<script src="hosts-template.js"></script>
<script src="hosts.js"></script>
<script>
function encode(str) {
    var mapping = {
        '*': '\\*',
        '.': '\\.'
    };

    var charArray = [];
    for (var i = 0; i < str.length; i++) {
        var ch = str.charAt(i);
        var encodedChar = mapping[ch] || ch;
        charArray.push(encodedChar);
    }

    var encoded = charArray.join('');
    console.info('encoded', '=>', encoded);
    return encoded;
}

/**
 * ';' => '<NEW_LINE>'
 */
function parseTemplate(str) {
    var lines = str.split(';');
    return lines.join('\n');
}

/**
 * '<NEW_LINE>' => ';\<NEW_LINE>'
 */
function formatTemplate(str, lineSeparator) {
    var regexp = /\n/g;
    var replacement = ';\\' + lineSeparator;
    var output = str.replace(regexp, function(str) {
        return replacement;
    });

    output = 'var templateString = "\\' + lineSeparator
        + output + '";';

    return output;
}

function generateTemplate() {
    var srcString = dijit.byId('editor').get('value');
    console.debug('src content', '=>', srcString);

    var output = formatTemplate(srcString, '\n');
    dijit.byId('outEditor').set('value', output);
}

/**
 *
 */
function selectPattern(pattern) {
    console.info('pattern', '=>', pattern);
    var patternSelector = dijit.byId('pattern');
    var store = patternSelector.store;
    var selectedItem = patternSelector.get('item') || null;
    console.debug('item', '=>', selectedItem);
    var ip = store.getValue(selectedItem, 'ip');
    var replacementBox = dijit.byId('replacement');
    replacementBox.set('value', ip);
}

function formatContent(content, pattern, replacement) {
    var regexp = new RegExp(encode('{' + pattern + '}'), 'g');
    var output = content.replace(regexp, function(str) {
        return replacement;
    });

    return output;
}

/**
 *
 */
function replaceHost() {
    var pattern = dijit.byId('pattern').get('value');
    console.info('pattern', '=>', pattern);

    var replacement = dijit.byId('replacement').get('value');
    console.info('replacement', '=>', replacement);

    var content = dijit.byId('editor').get('value');
    var output = formatContent(content, pattern, replacement);
    dijit.byId('outEditor').set('value', output);
}

/**
 *
 */
function replaceAllHosts() {
    var patternSelector = dijit.byId('pattern');
    var store = patternSelector.store;

    store.fetch({
        onComplete: function(items, request) {
            console.debug('items:', items.length);

            var content = dijit.byId('editor').get('value');
            dojo.forEach(items, function(item) {
                var pattern = store.getValue(item, 'host');
                console.info('pattern', '=>', pattern);
                var replacement = store.getValue(item, 'ip');
                console.info('replacement', '=>', replacement);

                content = formatContent(content, pattern, replacement);
            });
            dijit.byId('outEditor').set('value', content);
        }
    });
}
</script>

<!-- dojo ready -->
<script>
dojo.ready(function() {
    dojo.byId('version').innerHTML = 'Version ' + dojo.version;

    // load template
    var editor = dijit.byId('editor');
    editor.set('value', parseTemplate(templateString));

    // load mapping
    if (!hosts) {
        console.error('hosts is undefined!');
        return;
    }

    // create data store
    var items = [];
    for (var host in hosts) {
        var item = {
            'host': host,
            'ip': (hosts[host] || null)
        };
        items.push(item);
    }

    var data = {
        identifier: 'host',
        label: 'host',
        items: items
    };
    var store = new dojox.data.AndOrWriteStore({data: data});

    var combobox = dijit.byId('pattern');
    combobox.set("store", store);
});
</script>

  <!-- end scripts-->

  <!--[if lt IE 7 ]>
    <script src="js/libs/dd_belatedpng.js"></script>
    <script>DD_belatedPNG.fix("img, .png_bg"); // Fix any <img> or .png_bg bg-images. Also, please read goo.gl/mZiyb </script>
  <![endif]-->

</body>
</html>
